package com.waves.task.strategy.receive;

import com.waves.core.constant.RedisKey;
import com.waves.core.constant.redis.TaskRedisKey;
import com.waves.core.web.domain.R;
import com.waves.task.domain.entity.Task;
import com.waves.task.domain.enums.ReceiveTypeEnum;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Component
public class ReceiveSemaphoreStrategy extends AbstractReceiveStrategy {

    @Resource
    private RedissonClient redissonClient;


    @Override
    ReceiveTypeEnum getReceiveTypeEnum() {
        return ReceiveTypeEnum.RECEIVE_SEMAPHORE;
    }

    /**
     * 通过redis的信号量方式领取任务
     *
     * @param task
     * @return
     */
    @Override
    public R<Object> receiveTask(Task task) {
        String key = RedisKey.getKey(TaskRedisKey.TASK_RECEIVE_NUM, task.getId());
        RSemaphore semaphore = redissonClient.getSemaphore(key);
        // 申请，任务数量减一
        try {
            semaphore.tryAcquire(2, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            throw new RuntimeException("任务领取失败");
        }
        return super.saveTaskReceive(task);
    }

    @Override
    public void cancelTask(Task task) {
        String key = RedisKey.getKey(TaskRedisKey.TASK_RECEIVE_NUM, task.getId());
        RSemaphore semaphore = redissonClient.getSemaphore(key);
        // 释放，任务数量加一
        semaphore.release();
    }

    @Override
    public void createTask(Task task) {
        String key = RedisKey.getKey(TaskRedisKey.TASK_RECEIVE_NUM, task.getId());
        RSemaphore semaphore = redissonClient.getSemaphore(key);
        // 设置信号量数量
        semaphore.trySetPermits(task.getBountyNum() != null ? task.getBountyNum() : task.getHelpBountyNum());
    }
}
